package com.spring.arch.uaa.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.spring.arch.common.enums.Gender;
import com.spring.arch.common.idgenerator.IdGenerator;
import com.spring.arch.uaa.enums.CreateType;
import com.spring.arch.uaa.enums.OrganizationType;
import com.spring.arch.uaa.model.OrganizationEmployee;
import com.spring.arch.uaa.model.Project;
import com.spring.arch.uaa.model.TenantEmployee;
import com.spring.arch.common.enums.Gender;
import com.spring.arch.common.idgenerator.IdGenerator;
import com.spring.arch.uaa.enums.CreateType;
import com.spring.arch.uaa.enums.OrganizationType;
import com.spring.arch.uaa.model.*;
import com.spring.arch.uaa.repository.OrganizationEmployeeRepository;
import com.spring.arch.uaa.repository.OrganizationRepository;
import com.spring.arch.uaa.repository.TenantEmployeeRepository;
import com.spring.arch.uaa.repository.UserRepository;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author: nandy
 * @createDate: 2019/11/4 17:19
 * @description:
 */
@Setter
public class TenantEmployeeListener extends AnalysisEventListener<TenantEmployeeExportBean> {

    List<TenantEmployeeExportBean> list = new ArrayList<>();

    private TenantEmployeeRepository tenantEmployeeRepository;

    private UserRepository userRepository;

    private OrganizationRepository organizationRepository;

    private OrganizationEmployeeRepository organizationEmployeeRepository;

    private Tenant tenant;

    private Organization rootOrganization;

    private Project project;


    public List<TenantEmployeeExportBean> getList() {
        return list;
    }

    @Transactional
    @Override
    public void invoke(TenantEmployeeExportBean data, AnalysisContext analysisContext) {

        /*if(StringUtils.isBlank(data.getCode())) {

            data.setResult("失败");
            data.setReason("工号不能为空");

        } else if(repository.existsByCodeAndTenant(data.getCode(), tenant)) {

            data.setResult("失败");
            data.setReason("工号不能重复");

        } else*/
        if(StringUtils.isBlank(data.getMobile())) {

            data.setResult("失败");
            data.setReason("手机号码不能为空");

        } else if(tenantEmployeeRepository.existsByMobileAndTenant(data.getMobile(), tenant)) {

            data.setResult("失败");
            data.setReason("手机号码不能重复");

        } else if(StringUtils.isBlank(data.getCompany())) {

            data.setResult("失败");
            data.setReason("company不能为空");

        } else if(StringUtils.isBlank(data.getRealname())) {

            data.setResult("失败");
            data.setReason("姓名不能为空");

        } else if(data.getGender() != 0 && data.getGender() != 1 && data.getGender() != 2) {

            data.setResult("失败");
            data.setReason("性别只能是0、1或者2");

        } else {

            TenantEmployee tenantEmployee = new TenantEmployee();
            tenantEmployee.setTenant(tenant);
            tenantEmployee.setCode(IdGenerator.uniqueCode());
            tenantEmployee.setName(data.getRealname());
            tenantEmployee.setMobile(data.getMobile());
            tenantEmployee.setGender(1 == (data.getGender()) ? Gender.MALE : 0 == (data.getGender()) ?
                    Gender.FEMALE : Gender.OTHER);
            tenantEmployee.setEmail(data.getEmail());
            tenantEmployee.setCreateType(CreateType.IMPORT);
            tenantEmployee.setStatus(true);

            tenantEmployeeRepository.save(tenantEmployee);

            User user = new User();
            user.setMobile(data.getMobile());
            user.setRealName(data.getRealname());
            user.setPassword(data.getPassword());
            user.setSalt(data.getSalt());
            user.setEmail(data.getEmail());
            user.setGender(1 == (data.getGender()) ? Gender.MALE : 0 == (data.getGender()) ?
                    Gender.FEMALE : Gender.OTHER);

            userRepository.save(user);

            String[] companyArray = data.getDepartment().split("/");

            Organization parentOrganization = rootOrganization;

            for(int i = 0; i < companyArray.length; i++) {

                Optional<Organization> organizationOptional =
                        organizationRepository.findByParentAndNameAndDisableFalse(parentOrganization, companyArray[i]);

                if(organizationOptional.isPresent()) {

                    parentOrganization = organizationOptional.get();

                } else {

                    Organization organization = new Organization();

                    organization.setTenant(tenant);
                    organization.setParent(parentOrganization);
                    organization.setProject(project);
                    organization.setCode(IdGenerator.uniqueCode());
                    organization.setName(companyArray[i]);
                    organization.setType(OrganizationType.FUNCTION);

                    parentOrganization = organizationRepository.saveAndFlush(organization);
                }

                if(i == companyArray.length - 1) {

                    OrganizationEmployee organizationEmployee = new OrganizationEmployee();

                    organizationEmployee.setOrganization(parentOrganization);
                    organizationEmployee.setEmployee(tenantEmployee);
                    organizationEmployee.setUser(user);

                    organizationEmployeeRepository.save(organizationEmployee);
                }
            }


            try {

                data.setResult("成功");

            } catch(Exception e) {

                data.setResult("失败");
                data.setReason("未知原因，请联系管理员");
            }
        }

        list.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }
}
